<template>
  <div class="page-content">
    <!-- 表格顶部区域 -->
    <TableBar
      :columns="columns"
      @changeColumn="(newcolumns) => (this.columns = newcolumns)"
      :layout="layout"
    >
      <div slot="bottom">
        <el-row>
          <el-col :span="6">
            <el-button type="primary" plain size="mini" @click="dialog" v-auth="'order_info_insert'"
              >新增</el-button
            >
          </el-col>
        </el-row>
      </div>
      <div slot="top">
        <el-form label-width="55px">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="搜索">
                <el-input placeholder="请输入关键字" v-model="key"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6">
              <!-- <el-form-item label="地址：">
                <el-input placeholder="地址"></el-input>
              </el-form-item> -->
            </el-col>
            <el-row
              :xs="24"
              :sm="12"
              :lg="6"
              style="float: right; margin-right: 10px"
            >
              <el-button type="primary" @click="setAllList" v-auth="'order_info_select'">搜索</el-button>
              <el-button
                @click="
                  () => {
                    this.key = '';
                    this.setAllList();
                  }
                "
                v-auth="'order_info_select'"
                >重置</el-button
              >
            </el-row>
          </el-row>
        </el-form>
      </div>
    </TableBar>
    <!-- 表格区域 -->
    <TheTable
      :data="allList"
      :page.sync="page"
      :showPage="showPage"
      @changeSize="
        (size) => {
          this.page.pageSize = size.pageSize;
          this.setAllList();
        }
      "
      @changePage="
        (page) => {
          this.page.current = page.current;
          this.setAllList();
        }
      "
      :Bottom="35"
    >
      <!-- 点击表格单行显示详情 -->
      <div class="item" effect="dark" placement="top-start">
        <el-table-column type="expand" fixed="left">
          <template slot-scope="scope">
            <el-form label-position="left" class="demo-table-expand">
              <ShowRow
                :columns="showColumns"
                :row="scope.row"
                num="3"
                :key="scope.row.id"
              >
                <el-button
                  slot="slot1"
                  icon="el-icon-coordinate"
                  v-auth="'order_info_select'"
                  @click="
                    showMapCenterPoint = {
                      lat: scope.row['receiveLatitude'] || '23.12908',
                      lng: scope.row['receiveLongitude'] || '113.26436',
                      content: scope.row['receiveAddress'],
                    };
                    showMapDialog = true;
                  "
                  >地图</el-button
                >
              </ShowRow>
            </el-form>
          </template>
        </el-table-column>
      </div>
      <!-- 表格区域 -->
      <div
        v-for="item in showColumns"
        :key="item.name"
        class="item"
        effect="dark"
        placement="top-start"
      >
        <el-table-column
          v-if="item.show"
          :label="item.name"
          :prop="item.prop"
          show-overflow-tooltip
          :formatter="columnFormat"
          sortable
        ></el-table-column>
      </div>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            mini
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="dialog(scope.row)"
            v-auth="'order_info_update'"
          ></el-button>
          <el-button
            mini
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="delInfo(scope.row.id)"
            v-auth="'order_info_delete'"
          ></el-button>
        </template>
      </el-table-column>
    </TheTable>
    <!-- 对话框区域 -->
    <el-dialog
      :title="dialogTitle"
      width="60%"
      :visible.sync="showDialog"
      top="20vh"
      @close="
        () => {
          this.showDialog = false;
          this.form = {};
        }
      "
    >
      <el-form
        label-position="right"
        ref="formRef"
        :rules="rules"
        :model="form"
        label-width="135px"
      >
        <FormRow :form="form" :label-prop="formRowColumns"></FormRow>
        <el-form-item label="收货地址" prop="receiveAddress">
          <el-select
            v-model="form.receiveAddress"
            placeholder="请选择收货地址"
            style="width: 100%"
            filterable
            :filter-method="
              (keywords) => {
                this.mapKeywordsSearch = keywords;
              }
            "
          >
            <el-option
              v-for="item in adrsOptions"
              :key="item.id"
              :label="item.address"
              :value="item.address"
              @click.native="setReceiveAddress(item)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <MyLocationPicker
          @getCenterAddress="getCenterAddress"
          @getAroundPoi="(array_pois) => (this.adrsOptions = array_pois)"
          @getInputTip="(array_tips) => (this.adrsOptions = array_tips)"
          :selectedLocation="centerLocation"
          :keywords="mapKeywordsSearch"
          :initPoint="{
            lat: '23.12908',
            lng: '113.26436',
          }"
        ></MyLocationPicker>
        <!-- lat: this.form.receiveLatitude || '23.12908',
            lng: this.form.receiveLongitude || '113.26436', -->
        <el-form-item size="large" class="dialog-bottom-btn">
          <el-button type="primary" @click="submit" v-auth="'order_info_insert'">确定</el-button>
          <el-button @click="showDialog = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 显示地图弹框 -->
    <ShowFile
      :dialogVisible="showMapDialog"
      :close="() => (showMapDialog = false)"
      fileType="map"
      :centerPoint="showMapCenterPoint"
    ></ShowFile>
  </div>
</template>

<script>
import {
  getAllInfoByPage,
  getAllSupplier,
  getAllProduct,
  addInfo,
  delInfoById,
  editInfo,
  getColumns,
  rules
} from "../../Api/ordermanage/order_infomation";
import { getAllInfoByPage as getTargetList } from "../../Api/ordermanage/customer_infomation";
import MyLocationPicker from "../../components/OrderManagement/MyLocationPicker";
import Map from "../../components/OrderManagement/Map";
import FormRow from "../../components/OrderManagement/FormRow";
import ShowRow from "../../components/OrderManagement/ShowRow";
import ShowFile from "../../components/RightsManagement/BaseFileMange/ShowFile";

export default {
  name: "OrderInformation",
  components: {
    Map,
    MyLocationPicker,
    FormRow,
    ShowRow,
    ShowFile,
  },
  data() {
    return {
      allList: [],
      key: "", //关键字查询(收货人的名字，订单id，收货号码)
      columns: getColumns(this),
      layout: "search, refresh, column",
      form: { receiveAddress: "" },
      rules ,
      showPage: true, // 显示分页
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      processId: "",
      //   -------------form表单弹窗-------------
      showDialog: false,
      dialogTitle: "新增",
      adrsOptions: [],
      centerLocation: {},
      mapKeywordsSearch: "",
      // -----------地图弹窗----------
      showMapDialog: false,
      showMapCenterPoint: {},
    };
  },
  computed: {
    // 过滤不需要展示在表格的字段
    showColumns() {
      const noArr = ["productId", "targetCustomerType", "targetId", "sourceId"];
      return this.columns.filter((item) => {
        return !noArr.includes(item.prop);
      });
    },
    // 过滤掉发送请求时才加的表单字段
    formRowColumns() {
      const noArr = [
        "id",
        "gmtCreate",
        "productName",
        "targetName",
        "orderStatus",
        "receiveLatitude",
        "receiveLongitude",
        "receiveAddress",
        "addressCity",
        "addressProvince",
      ];
      return this.columns.filter((item) => {
        return !noArr.includes(item.prop);
      });
    },
  },
  methods: {
    // 获取数据 设置表格数据allList
    async setAllList() {
      const { data: res } = await getAllInfoByPage(
        this.page.current,
        this.page.pageSize,
        this.key
      );
      console.log("setAllList: ", res);
      if (res.statusCode !== 20000) {
        console.error(res.message);
      }
      this.allList = res.data.list;
      this.page.total = res.data.total;
    },
    // 设置目标列表 targetList
    async setTargetList(value) {
      // console.log('value: ', value);
      delete this.form.targetName; // 选择目标类型的时候，！！直接删除！！目标列表的值
      let type = value == 1 ? "personal" : "company";
      this.columns[8].select.label =
        this.form.targetCustomerType == 1 ? "customerName" : "companyName";
      const { data: res } = await getTargetList(
        this.page.current,
        this.page.pageSize,
        type
      );
      console.log("setTargetList: ", res);
      if (res.statusCode !== 20000) {
        console.error(res.message);
      }
      this.columns[9].select.options = res.data.list;
    },
    // 设置产品下拉框
    async setProductOptions() {
      const { data: res } = await getAllProduct();
      console.log("setProductOptions: ", res);
      if (res.statusCode !== 20000) {
        console.error(res.message);
      }
      this.columns[3].select.options = res.data;
    },
    // 设置供应商下拉框
    async setSuppliersOptions() {
      const { data: res } = await getAllSupplier();
      console.log("setSuppliersOptions: ", res);
      if (res.statusCode !== 20000) {
        console.error(res.message);
      }
      this.columns[14].select.options = res.data;
    },
    // 打开弹窗
    dialog(row = undefined) {
      row instanceof Event ? (row = {}) : "";
      console.log("row: ", row);
      let form = JSON.parse(JSON.stringify(row));
      console.log("form: ", form);
      if (row.id) {
        // 修改
        this.form = form;
        this.dialogTitle = "修改";
      } else {
        // 增加
        this.dialogTitle = "新增";
      }
      this.showDialog = true;
    },
    // 提交按钮
    async submit() {
      console.log("this.form: ", this.form);
      // return;
      this.$refs.formRef.validate(async (access, obj) => {
        if (access) {
          let res;
          if (!this.form.id) {
            // 增加
            res = await addInfo(this.form);
          } else {
            // 修改
            res = await editInfo(this.form);
          }
          res = res.data;
          if (res.statusCode !== 20000) {
            console.error(res.message);
            this.$message.error(res.message);
          } else {
            this.showDialog = false;
            this.$message.success(res.message);
            this.setAllList();
          }
        }
      });
    },
    // 删除按钮
    async delInfo(id) {
      this.$confirm("此操作将永久删除该信息，请谨慎操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await delInfoById(id);
          console.log("res: ", res);
          if (res.statusCode !== 20000) {
            this.$message.error(res.message);
          } else {
            this.setAllList();
            this.$message.success(res.message);
          }
        })
        .catch(() => {
          return this.$message.info("已取消删除！");
        });
    },
    // 点击下拉选择框时，设置form，地图中心点centerLocation
    setReceiveAddress(adrs) {
      console.log("adrs: ", adrs);
      this.form.receiveAddress = adrs.address;
      this.form.addressCity = adrs.ad_info ? adrs.ad_info.city : adrs.city;
      this.form.addressProvince = adrs.ad_info
        ? adrs.ad_info.province
        : adrs.province;
      this.form.receiveLatitude = adrs.location.lat;
      this.form.receiveLongitude = adrs.location.lng;
      this.form = { ...this.form };
      this.centerLocation = adrs.location;
    },
    // 移动地图的时候，设置form
    getCenterAddress(zh_address, location, origin) {
      console.log("location: ", location);
      console.log("origin: ", origin);
      console.log("zh_address: ", zh_address);
      this.form.receiveAddress = zh_address;
      this.form.addressCity = origin.address_component.city;
      this.form.addressProvince = origin.address_component.province;
      this.form.receiveLatitude = location.lat;
      this.form.receiveLongitude = location.lng;
      this.form = { ...this.form };
    },
    // 格式化表格
    columnFormat(row, columns, cellValue, index) {
      let { property } = columns;
      if (property == "orderStatus") {
        return row[property] == 1 ? "未送达" : "已送达";
      }
      return row[property];
    },
  },
  created() {
    this.setAllList();
    // 初始化一些选择框(由于展开行也需要options数组，所以不能等到弹窗打开再请求)
    this.setSuppliersOptions();
    this.setProductOptions();
  },
};
</script>

<style lang="scss" scoped>
.el-form .el-form-item .el-input {
  width: 300px;
}
>>> .select-width {
  width: 100%;
}
.dialog-bottom-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  >>> .el-form-item__content {
    margin-left: 0 !important;
    margin-top: 20px;
  }
}
</style>